package org.example.util;


import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.security.Keys;
import org.example.text.Convert;

import javax.crypto.SecretKey;
import java.nio.charset.StandardCharsets;
import java.util.Map;

public class JwtUtil {

	private static final String secret = "spring-boot-2025-jjwt-security-demo-org-example-start";

	private static final String userKey = "user_key";


	/**
	 * 根据数据生成token令牌
	 * secret为自定义加密字符串
	 */
	public static String createToken(Map<String, Object> claims) {
		String token = Jwts.builder().setClaims(claims).signWith(SignatureAlgorithm.HS512, secret).compact();
		return token;
	}

	/**
	 * 根据token解析出数据
	 * secret为自定义加密字符串
	 */
	public static Claims parseToken(String token) {
		SecretKey key = Keys.hmacShaKeyFor(secret.getBytes(StandardCharsets.UTF_8));
		return Jwts.parser().setSigningKey(key).build().parseClaimsJws(token).getBody();
	}

	public static String getUserKey(Claims claims) {
		return getValue(claims, userKey);
	}

	public static String getValue(Claims claims, String key) {
		return Convert.toStr(claims.get(key), "");
	}
}
